<?php

defined('BASEPATH') or die('forbidden');

class Cdkey_Controller Extends Controller {

    private $inc;
    private $center_connect;

    function _init() {
        check_level(50, segment(0), segment(1, 'index'));

        $this->inc = $this->config['inc'];
        $this->center_connect = $this->load->database('center_db'); 
		$this->objectlist= get_type_object_dynamic();
    }

    function index() {
        //echo $this->dbname;
        $this->view->display("freegift/cdkey/index");
    }

    function flexigrid() {
        //读取flexigrid传输的数据
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
        $rows = array();
        $sql = "SELECT COUNT(id) AS num FROM cdkey WHERE {$where}";
        $one = $this->center_connect->one($sql);
        $total = $one['num'];
        $orderby = $sortname ? "ORDER BY {$sortname} {$sortorder} " : "ORDER BY ID asc";
        $sql = "SELECT {$colsinfo} FROM cdkey WHERE {$where} {$orderby} LIMIT {$offset},{$rp}";
        $this->center_connect->query($sql);
        //echo ($sql) ;
        $sql = "SELECT * FROM cdkey_type";
        $this->center_connect->query($sql,"cdkey_type");
        while ($n = $this->center_connect->get_array("cdkey_type")){
            $keyTypes[$n['type']] = $n['name'];
        }
        while ($n = $this->center_connect->get_array('default')) {
            $n['starttime'] = get_datetime($n['starttime']);
            $n['endtime'] = get_datetime($n['endtime']);
            $n['isuse'] = $n['isuse'] == 0 ? "<label style='color:#FF0000'>未使用</label>" : "<label style='color:#999999'>已使用</label>";
            $n['keytype'] = $keyTypes[$n['keytype']].'-('.$n['keytype'].')';
			$n['rewardobjectid']= $this->objectlist[$n['rewardobjectid']].'-('.$n['rewardobjectid'].')';
            $rows[] = array('id' => $n['id'], 'cell' => ($n));
        }
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
        );
        echo json_encode($result);
    }

    function add($id = 0) {
        set_time_limit(0);
        //是否来源于表单请求
        if (is_submit()) {
            $rowdata = $_POST['row'];
            unset($cdkey_array);
            $cdkey_array = $this->cdkeyarray();
            //print_r($cdkey_array);
			$sq = "insert into cdkey (keyChar, 
									areaid, 
									keytype, 
									starttime, 
									endtime, 
									rewardobjectid, 
									isuse, 
									roleid) values";
            $num = $rowdata['num'];
			$issame=$rowdata['issame'];	//是否产生相同的
            $starttime = strtotime($rowdata['starttime']);
            $endtime = strtotime($rowdata['endtime']);
			
			//如果是产生相同的
			if($issame==1)	
			{
				$str = $this->create_swapcode(8);
				if (isset($cdkey_array[$str]) == true) {
					while (isset($cdkey_array[$str]) == true) {
						$str = $this->create_swapcode(8);
					}
				}
			}
			
            while ($num) {
				//如果是产生不同的	
				if($issame!=1)	{
					$str = $this->create_swapcode(8);
					if (isset($cdkey_array[$str]) == true) {
						while (isset($cdkey_array[$str]) == true) {
							$str = $this->create_swapcode(8);
						}
					}
				}
                $cdkey_array[$str] = $str;
                $sq.="('" . $str . "',
            				'" . $rowdata['areaid'] . "',
            				'" . $rowdata['keytype'] . "',
            				'" . $starttime . "',
            				'" . $endtime . "',
            				'" . $rowdata['rewardobjectid'] . "',
            				0,
            				0 ), ";
                $num = $num - 1;
            }
            $sql = substr($sq, 0, -2);
            //更新数据表
            $id = $this->center_connect->query($sql);
            unset($cdkey_array);
            insert_log(translate('MENU_REWARD_CDKEY'),translate('ADD'), $rowdata);
            cp_tips("success", $id);
        }
        $sql = "select type,name from cdkey_type group by type";
        $this->center_connect->query($sql);
        $type = $this->center_connect->row('default');
        foreach ($type as $key => $value) {
            $cdkeytype[$value['type']] = $value['type']."-".$value['name'];
        }
        $sql = "select id,name from dynamic_type_object group by id";
        $this->center_connect->query($sql);
        $object = $this->center_connect->row('default');
        foreach ($object as $k => $w) {
            $rewardobjectid[$w['id']] = $w['id'].'-'.$w['name'];
        }
		$this->load->database('db');
        $arealist = get_area_list_option();
        //print_r($arealist);
        $arealist = array_merge(array("0" => translate("ALL_AREA")), $arealist);
        //print_r($arealist);
        $this->view->assign('rewardobjectid', $this->form->select("row[rewardobjectid]", $rewardobjectid, '', array('id' => 'rewardobjectid')));
        $this->view->assign('cdkeytype', $this->form->select("row[keytype]", $cdkeytype, '', array('id' => 'keytype')));
        $this->view->assign("areaid", $arealist);
        //print_r($arealist);
        $this->view->display("freegift/cdkey/add");
    }

    function edit($id = 0) {
        $c = 0;
        if ($id === 0)
            error(translate('C_INVALID_PARAM_ID', $id));
        $row = $this->center_connect->one("SELECT * FROM cdkey WHERE id='{$id}'");
        if (!is_array($row))
            error(translate('C_INVALID_PARAM_ID', $id));
        else if ($row['isuse'] == 1) {
            echo translate('FREEGIFT_CDKEY_ISUSE');
            return;
        }
        //是否来源于表单请求
        if (is_submit()) {
            $rowdata = $_POST['row'];
            //更新数据表
            $rowdata['starttime'] = strtotime($rowdata['starttime']);
            $rowdata['endtime'] = strtotime($rowdata['endtime']);
            $result = $this->center_connect->update("cdkey", $rowdata, array('id' => $id));

            insert_log(translate('MENU_REWARD_CDKEY'),translate('EDIT'), $row, $rowdata);
            cp_tips("success", $id);
        }
        $sql = "select type,name from cdkey_type group by type";
        $this->center_connect->query($sql);
        $type = $this->center_connect->row('default');
        foreach ($type as $key => $value) {
            $cdkeytype[$value['type']] = $value['name'];
        }
        $sql = "select id,name from dynamic_type_object group by id";
        $this->center_connect->query($sql);
        $object = $this->center_connect->row('default');
        foreach ($object as $k => $w) {
            $rewardobjectid[$w['id']] = $w['name'];
        }
        $this->view->assign('rewardobjectid', $this->form->select("row[rewardobjectid]", $rewardobjectid, $row['rewardobjectid'], array('id' => 'rewardobjectid')));
        $this->view->assign('cdkeytype', $this->form->select("row[keytype]", $cdkeytype, $row['keytype'], array('id' => 'keytype')));
        $this->view->assign("areaid", $this->form->select("row[areaid]", array_merge(array(0 => translate('FREEGIFT_AREA_ALL')), get_area_list_option()), $row['areaid'], array('id' => 'areaid')));
		$this->view->assign('keyChar', $row['keyChar']);
        $this->view->assign('starttime', get_datetime($row['starttime']));
        $this->view->assign('endtime', get_datetime($row['endtime']));
        $this->view->display("freegift/cdkey/edit", array('row' => $row));
    }

    function del($id = 0) {
        $c = 0;
        $r = '';
        if ($id === 0)
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        $row = $this->center_connect->one("SELECT id,isuse FROM cdkey WHERE id='{$id}'");
        if (!is_array($row))
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        else if ($row['isuse'] == 1) {
            json_output($c, translate('FREEGIFT_CDKEY_ISUSE', $id));
            exit();
        }
        if ($this->center_connect->delete("cdkey", array('id' => $id))) {
            insert_log(translate('MENU_REWARD_CDKEY'),translate('DEL'), array('id'=>$id));
            $c = 1;
        } else {
            $r = translate('C_TIPS_ERROR_TEXT');
        }
        json_output($c, $r);
    }

    function multi() {
        $type = $this->input->post("type");
        $ids = $this->input->post("ids");
        $c = 0;
        $r = '';
        $allids = $ids = explode(',', $ids);
        if (count($ids) == 0) {
            $r = translate('C_INVALID_PARAMS');
        } else {
            $ids = "'" . implode("','", $ids) . "'";
            if ($type == 'delete') {
                $this->center_connect->query("DELETE FROM cdkey WHERE id IN ({$ids}) and isuse=0");
                insert_log(translate('MENU_REWARD_CDKEY'),translate('MULTI_DEL'), array('ids'=>implode(",", $allids)));
                $c = 1;
            } else {
                $r = translate('C_INVALID_PARAMS');
            }
        }

        json_output($c, $r);
    }

    //------------激活码---------------------
    function create_swapcode($len) {
        $swapcode = '';
        /*
          $arrays = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9');
          for ($i = 0; $i < $len; $i++)
          {
          $key = rand(0,35);
          $swapcode .= $arrays[$key];
          }
         */
        $chars = 'abcdefghijklmnopqrstuvwxyz';
        for ($i = 0; $i < $len - 4; $i++) {
            $swapcode .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        $chars = '0123456789';
        for ($i = 0; $i < 4; $i++) {
            $swapcode .= $chars[mt_rand(0, strlen($chars) - 1)];
        }

        return $swapcode;
    }

    function cdkeyarray() {
        $sql = "select keyChar from cdkey";
        $this->center_connect->query($sql);
        $row = $this->center_connect->row('default');

        foreach ($row as $k => $v) {
			$cdkeyarray[$v['keyChar']] = $v['keyChar'];
        }
        return $cdkeyarray;
    }

}
